/**
 * JavaScript array library.
 * @author shenw
 */
(function(){
	var root = pack('jshen.array');
	/**
	 * Add element from src array to desc array.
	 * @param {Array} srcArray
	 * @param {int} beginIndex
	 * @param {int} length
	 */
	Array.method('add',function(src, beginIndex, length){
		var s,l;
		if (!beginIndex) {
			beginIndex = 0;
		}
		if (!length) {
			length = src.length;
		}
		for (var i = 0; i < length; i++) {
			this.push(src[i+beginIndex]);
		}
		return this;
	});
	/**
	 * Found index of the value in array.
	 * @param {Object} value
	 * @return {int} index(if can not found, return -1)
	 */
	Array.method('index', function(value){
		for (var i=0; i < this.length; i++) {
			if (value === this[i]) {
				return i;
			}
		}
		return -1;
	});
	/**
	 * Detect object is array.
	 * @param {Object} value
	 */
	root.method('isArray', function(value){
	    return value &&
	    typeof value === 'object' &&
	    typeof value.length === 'number' &&
	    typeof value.splice === 'function' &&
	    !(value.propertyIsEnumerable('length'));
	});
	/**
	 * Delete object from array
	 * @param {Object} value
	 */
	Array.method('remove', function(value){
		var index = this.index(value);
		if (index < 0) {
			return false;
		} else {
			return this.removeIndex(index);
		}
	});
	/**
	 * Delete index from array
	 * @param {Object} index
	 */
	Array.method('removeIndex', function(index) {
		if(isNaN(index) || index>this.length || index<0) {
			return false;
		} else {
			this.splice(index, 1);
			return true;
		}
	});
	/**
	 * Obtain the intersection of two lists.
	 * @param {Object} list
	 */
	Array.method('intersection', function(list, type) {
		var checkType;
		if (typeof type === 'undefined') {
			checkType = false;
		} else {
			checkType = true;
		}
		
		var result = [];
		if (root.isArray(list)) {
			var a, b;
			if (this.length < list.length) {
				a = this;
				b = list;
			} else {
				a = list;
				b = this;
			}
			for (var i in a) {
				if (b.index(a[i]) >= 0 && (!checkType || typeof a[i] === type)) {
					result.push(a[i]);
				}
			}
			return result;
		} else {
			return null;
		}
	});
})();
